var code = require('./code.js');
var parsePosition = require('./parsePosition.js');
var parseBatchPosition = require('./parseBatchPosition.js');
var db = require('./db.js');

//消息头
function head(){
	this.Id = 0;
	this.BodyLength = 0;
	this.EncryptionMethod = 0;
	this.IsBag = true;
	this.TerminalPhoneNum = '';
	this.MsgNumber = 0;
	this.TotalBagNum = 1;
	this.PackageNumber = 1;
}

//完成分包、去标识位、转义、校验码校验、去掉校验码
var subpackage = function(buf){
	var _totallen = buf.length;
	var _foundhead = false;
	var _result = [];
	var _package = [];
	for(var i=0;i<_totallen;i++) {
		if (buf[i] == 126 ) {
			if(_foundhead){
				_foundhead = false;
				if (code.checkBytes(_package)) {//校验码校验
					_result.push( _package.slice(0, _package.length - 1) );
					return _result;
				} else {
					console.log('校验码校验错误！');
					return {error: true};
				}
			}else{
				_foundhead = true;
			}
		} else if (_foundhead) {
			if (buf[i] == 125) {//转义
				if (buf[i + 1] == 1) {
					_package.push(125);
				} else if (buf[i + 1] == 2) {
					_package.push(126);
				}
				i++;
			} else {
				_package.push(buf[i]);
			}
		}
	}

	return {error: true};
};

//终端注册
var login = function(body,head){
	//var body = {};
	body.terminalID = String.fromCharCode.apply(null,body.slice(29,36));
	var sim = head.TerminalPhoneNum;
	var terminalcode = body.terminalID;
	var verifycode = ''+ sim + terminalcode;
	var msgid = [0x81,0x00],
		phone = code.str2Bcd(sim),
		seiralnum = code.getSerialNumber(),
		msgnum = code.int2bytes2(head.MsgNumber),
		msgresult = code.int2bytes2(0)[1],
		msgveri = code.str2unicode(verifycode);
	var response = code.makeMessage(
		msgid,
		phone,
		seiralnum,
		[].concat(
			msgnum,
			msgresult,
			msgveri
		)
	);
	return response;
};

//终端注销
var logout = function(head){
	return code.makeMessage(
		[0x80,0x01],
		code.str2Bcd(head.TerminalPhoneNum),
		code.getSerialNumber(),
		[].concat(
			code.int2bytes2(head.MsgNumber),
			[0x00,0x03],
			0x00
		)
	);
};

// 终端鉴权
var authentication = function(body,head){
	db.sequelize.query("select v.UNIFICATIONCODE from T_VEHICLE v where v.TERMINALID = (select t.TERMINALID from T_TERMINAL t where t.sim="+head.TerminalPhoneNum+")"
		, { type: db.sequelize.QueryTypes.select })
		.then(function (results){
			console.log(results);
			var ifExits = false;
			//判断sim_unicode_cache是否有此辆车，如果有，不管，如果没有新增
			for (var i = 0; i < parsePosition.sim_unicode_cache.length; i++){
				if(parsePosition.sim_unicode_cache[i].UNIFICATIONCODE == results[0].UNIFICATIONCODE){
					ifExits = true;
					console.log("sim_unicode_cache存在此辆车");
				}
			}

			if(ifExits == false){
				console.log("sim_unicode_cache中不存在此辆车");
				parsePosition.sim_unicode_cache.push({
					SIM: head.TerminalPhoneNum,
					UNIFICATIONCODE: results[0].UNIFICATIONCODE
				})
			}
			//sim_unicode_cache = results[0];
			//console.log(sim_unicode_cache);
		});

	var response = code.makeMessage(
		[0x80,0x01],
		code.str2Bcd(head.TerminalPhoneNum),
		code.getSerialNumber(),
		[].concat(
			code.int2bytes2(head.MsgNumber),
			[0x01,0x02],
			0x00
		)
	);
	return response;
};

// 心跳
var heartbeat = function(head) {
	var response = code.generalResponse(
		[0x80, 0x01],
		code.str2Bcd(head.TerminalPhoneNum),
		code.getSerialNumber(),
		code.int2bytes2(head.MsgNumber),
		[0x00, 0x02],
		0x00
	);
	return response;
};

// 按消息id解析并返回
// 已简化，只处理最核心业务；
// 没有全部处理，待补充！
var classification = function(body, head){
	var res ;
	switch(head.Id){
		case 1: {// 终端通用应答
			break;
		}
		case 2: {// 终端心跳
			res  = heartbeat(head);
			break;
		}
		case 3: {// 终端注销
			res = logout(head);
			break;
		}
		case 256: {// 终端注册
			res = login(body,head);
			break;
		}
		case 258: {// 终端鉴权
			res = authentication(body,head);
			break;
		}
		case 260: {// 终端参数应答
			break;
		}
		case 512: {//解析位置
			res = parsePosition.parsePosition(body,head);
			break;
		}
		case 1796:{// 批量解析位置
			//res = parseBatchPosition.parseBatchPosition(body,head);
			break;
		}
		case 2304:{// 数据上传透传
			break;
		}
		case 513:{// 查询位置信息应答
			break;
		}
	}
	return res;
};

var analysis = function(buf){
	var packages = subpackage(buf);
	if(packages.error){
		return;
	}
	for(var i=0;i<packages.length;i++){
		var _p = packages[i];
		var _head = new head();
		_head.Id = code.bytes2int2([ _p[0] , _p[1] ]);
		_head.BodyLength = code.bytes2int2([ (_p[2] & 0x3) , _p[3] ]);
		_head.EncryptionMethod = _p[3] & 0x1C;
		_head.IsBag = (_p[2] & 0x20) != 0;
		_head.TerminalPhoneNum = code.bcd2Str( [_p[4],_p[5],_p[6],_p[7],_p[8],_p[9]] );
		_head.MsgNumber = code.bytes2int2( [ _p[10] , _p[11] ] );
		// 无分包
		if(!_head.IsBag){
			return  classification(_p.slice(12), _head);
		}
	}
};

module.exports = {
	analysis : analysis
};